[Coding028] Sort - 基数排序

Radix-sort

Ben 2024/01/22

More coding records

Get the knowledge flowing and circulating! :)

目录

标题:基数排序

Words & phrases

radix 美/ ˈreɪdɪks /

  • n.根;[数]基数

Radix sorting is widely used for its high efficiency.

基数排序由于其效率高而被广泛应用。

概念

基数排序(英语:Radix sort)是一种非比较型整数排序算法,其原理是将整数按位数切割成不同的数字,然后按每个位数分别比较。

  • 由于整数也可以表达字符串(比如名字或日期)和特定格式的浮点数,所以基数排序也不是只能使用于整数。

实现方法

  1. 将所有待比较数值(正整数)统一为同样的数位长度(数位较短的数前面补零)。

  2. 然后,从最低位开始,依次进行一次排序。

这样从最低位排序一直到最高位排序完成以后,数列就变成一个有序序列。


基数排序的方式可以采用LSD(Least significant digital)或MSD(Most significant digital):

  • LSD:LSD的排序方式由键值的最右边开始;

  • MSD:与LSD相反,由键值的最左边开始。

——维基百科

 

Radix-Sort Variation 1

variation 美/ ˌveriˈeɪʃ(ə)n /

  • n.变化,变动;变奏曲;变化,变异;(天文)二均差;(数)变分,变差;磁偏角;(芭蕾)单人舞

Variation among humans is limited to the possible permutations of our genes.

人类的变化形式受限于我们基因可能的那些排列。

image-20240122094343914

Radix-Sort Variation 2

image-20240122094731532

实例

(1001) (0010) (1101) (0001) (1110)

Sorting a sequence of 4-bit integers

image-20240122094954705

Radix-Sort Variation 3

The keys are integers in the range [0,N21]

We represent a key as a 2-tuple of digits in the range [0, N − 1] and apply radish-sort i.e. we write it in base N notation:

现在考虑一下泛化情况(即,以N为基的radish-sort),十进制的整数就拆成多个十进制的单个数,例如75 →(7, 5)

实例 (N = 10)

keys are integers in the range [0, 99]

75, 12, 54, 33, 14, 87, 45, 17

image-20240122095409869

拓展(Extensions)

Radix-sort string variation(适用于字符串的基数排序的变形

实例(Example)

Use the last variation to sort the following strings:

“cart ”, “core ”, “fore”, “cans”, “cars”, “bans”

image-20240122095622371